//
//  NXSixthStepViewController.m
//  BiologyLibrary
//
//  Created by milo on 16/7/5.
//  Copyright © 2016年 youxh. All rights reserved.
//

#import "NXSixthStepViewController.h"
#import "NXSeventhStepViewController.h"
#import "SelectTimeTableViewCell.h"
#import "TestTubeTableViewCell.h"
#import "TitleTableViewCell.h"
#import "SampleTitleTableViewCell.h"
#import "SelectCompleteTableViewCell.h"
@interface NXSixthStepViewController ()
{
    NSMutableArray *finish1Array;
    NSMutableArray *finish2Array;
    NSMutableArray *timeArray;
    NSInteger selectedIndex;
    NSInteger currentIndex;
}
@end

@implementation NXSixthStepViewController
static const NSString * KEY_STEP6  = @"step6";

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    NSLog(@"setp1 record === %@", self.NewRecordArray.firstObject.getDetailDict);
    [self setNaviBarTitle:self.NewRecordArray.firstObject.name];
    _maintableview=[[UITableView alloc]initWithFrame:CGRectMake(10, 64, fWidth_Current-20, fHeight_Current-64-50)];
    _maintableview.backgroundColor = [UIColor clearColor];
    _maintableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    _maintableview.dataSource = self;
    _maintableview.delegate = self;
    [self.view addSubview:_maintableview];
    
    UIImageView*buttomview=[[UIImageView alloc]initWithFrame:CGRectMake(0, fHeight_Current-50, fWidth_Current, 50)];
    buttomview.backgroundColor=[UIColor colorWithRed:0.16 green:0.19 blue:0.24 alpha:1.0];
    [self.view addSubview:buttomview];
    UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, fWidth_Current, 50)];
    label.backgroundColor=[UIColor clearColor];
    label.textAlignment=1;
    label.font=[UIFont systemFontOfSize:14];
    label.textColor=[UIColor lightGrayColor];
    label.text= [NSString stringWithFormat:@"当下是第%ld/%ld步",
                 (long)self.NewRecordArray.firstObject.savedStepCount + 1, (long)self.NewRecordArray.firstObject.allStepCount];
    [buttomview addSubview:label];
    finish1Array = [NSMutableArray arrayWithCapacity:0];
    finish2Array = [NSMutableArray arrayWithCapacity:0];
    timeArray = [NSMutableArray arrayWithCapacity:0];

    for (Record *model in self.NewRecordArray) {
        NSMutableArray *tmp = [NSMutableArray arrayWithCapacity:0];
        for (int i=0; i<3; i++) {
            [tmp addObject:@"1"];
        }
        [finish1Array addObject:tmp];
        [finish2Array addObject:@"1"];
        if ([[model getDetailDict] objectForKey:KEY_STEP6] &&
            [[[[model getDetailDict] objectForKey:KEY_STEP6] objectAtIndex:3] objectForKey:KEY_RECORD_ANSWER]) {
            [timeArray addObject:[[[[model getDetailDict] objectForKey:KEY_STEP6] objectAtIndex:3] objectForKey:KEY_RECORD_ANSWER]];
        }else
        {
            [timeArray addObject:@""];
        }

        NSLog(@"%@",model.recordId);
    }
}

#pragma mark - UITableViewDataSource

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section==0) {
        return 1+finish1Array.count*3+finish1Array.count;
    }else if (section == 1){
        return 1+timeArray.count*2;
    }else if(section == 2){
        return 1+finish2Array.count*2;
    }else
    {
        return 1;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 4;//返回标题数组中元素的个数来确定分区的个数
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section==0) {
        if (indexPath.row==0) {
            NSString*titlestr=@"6.1、取3x1mL囊液：";
             CGSize hight=[TGCDataCenter getContentSize:titlestr WithMaxSize:CGSizeMake(fWidth_Current-40, 1000) Font:[UIFont systemFontOfSize:17] LineBreakMode:NSLineBreakByWordWrapping];

            return 40+hight.height;
        }else if ((indexPath.row-1)%4==0)
        {
            return 40;
        }
        else{
            return 50;
        }
    }else if (indexPath.section == 1){
        if (indexPath.row == 0) {
            NSString*titlestr=@"6.2、囊液抽取时间。";
            CGSize hight=[TGCDataCenter getContentSize:titlestr WithMaxSize:CGSizeMake(fWidth_Current-40, 1000) Font:[UIFont systemFontOfSize:17] LineBreakMode:NSLineBreakByWordWrapping];
            return 40+hight.height;
        }else if (indexPath.row%2)
        {
            return 40;
        }else
        {
            return 50;
        }
        
    }else if (indexPath.section == 2){
        if (indexPath.row==0) {
            NSString*titlestr=@"6.3、装有囊液的1.5mL EP置于冰上临时保存。";
            
            CGSize hight=[TGCDataCenter getContentSize:titlestr WithMaxSize:CGSizeMake(fWidth_Current-40, 1000) Font:[UIFont systemFontOfSize:17] LineBreakMode:NSLineBreakByWordWrapping];
            
            return 40+hight.height;
            
        }else if (indexPath.row%2)
        {
            return 40;
        }
        else{
            return 50;;
        }
    }else {
        return 50;
        
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 10;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView*headview=[[UIView alloc]initWithFrame:CGRectMake(0, 0, fWidth_Current, 18)];
    headview.backgroundColor=[UIColor clearColor];
    return headview;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    switch (indexPath.section) {
        case 0:{
            
            if (indexPath.row==0) {
                TitleTableViewCell *cell = (TitleTableViewCell *)[self getCell:@"TitleTableViewCell"];
                
                NSString*titlestr=@"6.1、取3x1mL囊液：";
                cell.titleLab.text = titlestr;
                return cell;
            }else if((indexPath.row-1)%4!=0){
                TestTubeTableViewCell *cell = (TestTubeTableViewCell*)[self getCell:@"TestTubeTableViewCell"];
                
                NSInteger index = (indexPath.row-1)/4;
                NSInteger smallIndex = (indexPath.row-2)%4;
                WeakObj(finish1Array);
                WeakSelf;
                cell.yesBlock = ^{
                    NSMutableArray *mutableArray = [[finish1ArrayWeak objectAtIndex:index] mutableCopy];
                    [mutableArray replaceObjectAtIndex:smallIndex withObject:@"1"];
                    [finish1ArrayWeak replaceObjectAtIndex:index withObject:mutableArray];
                    [weakSelf creatDetailDict:weakSelf.NewRecordArray[index]];
                };
                cell.noBlock = ^{
                    NSMutableArray *mutableArray = [[finish1ArrayWeak objectAtIndex:index] mutableCopy];
                    [mutableArray replaceObjectAtIndex:smallIndex withObject:@"0"];
                    [finish1ArrayWeak replaceObjectAtIndex:index withObject:mutableArray];
                    [weakSelf creatDetailDict:weakSelf.NewRecordArray[index]];
                };
                cell.firstlab.text =[NSString stringWithFormat:@"%li号管:",smallIndex];
                if ([[self.NewRecordArray[index] getDetailDict] objectForKey:KEY_STEP6] &&
                    [[[[self.NewRecordArray[index] getDetailDict] objectForKey:KEY_STEP6] objectAtIndex:index] objectForKey:KEY_RECORD_ANSWER]) {
                    cell.onfinish = [[[[self.NewRecordArray[index] getDetailDict] objectForKey:KEY_STEP6] objectAtIndex:smallIndex] objectForKey:KEY_RECORD_ANSWER];
                }else if ([[self.NewRecordArray[index] getDetailDict] objectForKey:KEY_STEP6] == nil)
                {
                    cell.onfinish = @"1";
                }
                
                
                if (self.fromtype && [self.fromtype isEqualToString:@"search"]) {
                    cell.btnno.userInteractionEnabled = NO;
                    cell.btnyes.userInteractionEnabled = NO;
                }else{
                    cell.btnno.userInteractionEnabled = YES;
                    cell.btnyes.userInteractionEnabled = YES;
                }
                return cell;
            }
            else {
                SampleTitleTableViewCell *cell = (SampleTitleTableViewCell*)[self getCell:@"SampleTitleTableViewCell"];
                Record *nowrecord = self.NewRecordArray[(indexPath.row-1)/4];
                cell.titleLab.text = [NSString stringWithFormat:@"样本号：%@",nowrecord.recordId];
                return cell;
            }
        }
            break;
        case 1:{
            if (indexPath.row == 0) {
                TitleTableViewCell *cell = (TitleTableViewCell *)[self getCell:@"TitleTableViewCell"];
                
                NSString*titlestr=@"6.2、囊液抽取时间。";
                cell.titleLab.text = titlestr;
                return cell;
            }else if (indexPath.row%2)
            {
                SampleTitleTableViewCell *cell = (SampleTitleTableViewCell*)[self getCell:@"SampleTitleTableViewCell"];
                Record *nowrecord = self.NewRecordArray[(indexPath.row-1)/2];
                cell.titleLab.text = [NSString stringWithFormat:@"样本号：%@",nowrecord.recordId];
                return cell;
            }
            else
            {
                NSInteger index = (indexPath.row-2)/2;

                SelectTimeTableViewCell *cell = (SelectTimeTableViewCell *)[self getCell:@"SelectTimeTableViewCell"];
                if ([[self.NewRecordArray[index] getDetailDict] objectForKey:KEY_STEP6] &&
                    [[[[self.NewRecordArray[index] getDetailDict] objectForKey:KEY_STEP6] objectAtIndex:3] objectForKey:KEY_RECORD_ANSWER]) {
                    
                    cell.timeLabel.text = [[[[self.NewRecordArray[index] getDetailDict] objectForKey:KEY_STEP6] objectAtIndex:3] objectForKey:KEY_RECORD_ANSWER];
                }
                
                return cell;
            }
            
        }
            break;
        case 2:{
            if (indexPath.row==0) {
                NSString*titlestr=@"6.3、装有囊液的1.5mL EP置于冰上临时保存。";
                TitleTableViewCell *cell = (TitleTableViewCell *)[self getCell:@"TitleTableViewCell"];
                cell.titleLab.text = titlestr;
                return cell;
                
            }else if (indexPath.row%2)
            {
                SampleTitleTableViewCell *cell = (SampleTitleTableViewCell*)[self getCell:@"SampleTitleTableViewCell"];
                Record *nowrecord = self.NewRecordArray[(indexPath.row-1)/2];
                cell.titleLab.text = [NSString stringWithFormat:@"样本号：%@",nowrecord.recordId];
                return cell;
            }
            else{
                SelectCompleteTableViewCell *cell = (SelectCompleteTableViewCell*)[self getCell:@"SelectCompleteTableViewCell"];
                NSInteger index = (indexPath.row-2)/2;

                cell.idLabel.text = [NSString stringWithFormat:@"样本号：%@",self.NewRecordArray[index].recordId];

                if ([[self.NewRecordArray[index] getDetailDict] objectForKey:KEY_STEP6] &&
                    [[[[self.NewRecordArray[index] getDetailDict] objectForKey:KEY_STEP6] objectAtIndex:4] objectForKey:KEY_RECORD_ANSWER]) {
                    cell.onfinish = [[[[self.NewRecordArray[index] getDetailDict] objectForKey:KEY_STEP6] objectAtIndex:4] objectForKey:KEY_RECORD_ANSWER];
                }else if ([[self.NewRecordArray[index] getDetailDict] objectForKey:KEY_STEP6] == nil)
                {
                    cell.onfinish = @"1";
                }
                WeakObj(finish2Array);
                WeakSelf;
                cell.yesBlock = ^{
                    [finish2ArrayWeak replaceObjectAtIndex:index withObject:@"1"];
                    [weakSelf creatDetailDict:weakSelf.NewRecordArray[index]];
                };
                cell.noBlock = ^{
                    [finish2ArrayWeak replaceObjectAtIndex:index withObject:@"0"];
                    [weakSelf creatDetailDict:weakSelf.NewRecordArray[index]];
                };
                
                if (self.fromtype && [self.fromtype isEqualToString:@"search"]) {
                    cell.btnyes.userInteractionEnabled = NO;
                    cell.btnno.userInteractionEnabled = NO;
                }else{
                    cell.btnyes.userInteractionEnabled = YES;
                    cell.btnno.userInteractionEnabled = YES;
                }
                return cell;
            }
        }
            break;
        case 3:{
            UITableViewCell *cell = [_maintableview dequeueReusableCellWithIdentifier:@"cell"];
            if (cell == nil) {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                cell.backgroundColor=[UIColor colorWithRed:0.16 green:0.19 blue:0.24 alpha:1.0];
            }
            cell.backgroundColor=[UIColor clearColor];
            
            if (self.fromtype && [self.fromtype isEqualToString:@"search"]) {
                
                UIButton *btn2=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 50)];
                btn2.backgroundColor=[UIColor colorWithRed:0.22 green:0.57 blue:0.91 alpha:1.0];
                btn2.layer.cornerRadius=5;
                [btn2 setTitle:@"下一步" forState:UIControlStateNormal];
                btn2.clipsToBounds=YES;
                [btn2 addTarget:self action:@selector(nextStepClick) forControlEvents:UIControlEventTouchUpInside];
                [cell addSubview:btn2];
            }else{
                
                UIButton *btn1=[[UIButton alloc]initWithFrame:CGRectMake(0, 0, (fWidth_Current-30)/2, 50)];
                btn1.backgroundColor=[UIColor colorWithRed:0.16 green:0.19 blue:0.24 alpha:1.0];
                btn1.layer.cornerRadius=5;
                [btn1 setTitle:@"取消" forState:UIControlStateNormal];
                btn1.clipsToBounds=YES;
                [btn1 addTarget:self action:@selector(cancelclick) forControlEvents:UIControlEventTouchUpInside];
                [cell addSubview:btn1];
                UIButton *btn2=[[UIButton alloc]initWithFrame:CGRectMake((fWidth_Current-30)/2+10, 0, (fWidth_Current-30)/2, 50)];
                btn2.backgroundColor=[UIColor colorWithRed:0.22 green:0.57 blue:0.91 alpha:1.0];
                btn2.layer.cornerRadius=5;
                [btn2 setTitle:@"保存" forState:UIControlStateNormal];
                btn2.clipsToBounds=YES;
                [btn2 addTarget:self action:@selector(saveClick) forControlEvents:UIControlEventTouchUpInside];
                [cell addSubview:btn2];
            }
            return cell;
        }
            break;
            
        default:
            return nil;
            break;
    }
}

-(UITableViewCell *)getCell:(NSString *)strIdentifier
{
    UITableViewCell *cell = [_maintableview dequeueReusableCellWithIdentifier:strIdentifier];
    if (cell == nil) {
        cell = [[[NSBundle mainBundle]loadNibNamed:strIdentifier owner:self options:nil] firstObject];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor=[UIColor colorWithRed:0.16 green:0.19 blue:0.24 alpha:1.0];
    }
    return cell;

}
-(void)yesclick:(UIButton *)sender{
    sender.selected=YES;
//    if (sender == btnyes1) {
//        btnno1.selected=NO;
//        onefinished=@"1";
//    }else if(sender == btnyes2){
//        btnno2.selected=NO;
//        twofinished=@"1";
//
//    }else if(sender == btnyes3){
//        btnno3.selected=NO;
//        threefinished=@"1";
//
//    }else if(sender == btnyes4){
//        btnno4.selected=NO;
//        fourfinished=@"1";
//    }
}
-(void)noclick:(UIButton *)sender{
    sender.selected=YES;
//    if (sender == btnno1) {
//        btnyes1.selected=NO;
//        onefinished=@"0";
//
//    }else if(sender == btnno2){
//        btnyes2.selected=NO;
//        twofinished=@"0";
//    }else if(sender == btnno3){
//        btnyes3.selected=NO;
//        threefinished=@"0";
//    }else if(sender == btnno4){
//        btnyes4.selected=NO;
//        fourfinished=@"0";
//    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
     selectedIndex = indexPath.section;
     currentIndex = indexPath.row;
    if (indexPath.section == 1){
        if (self.fromtype && [self.fromtype isEqualToString:@"search"]) {
            
        }else{
            
            if (!_datePickAlertVC) {
                _datePickAlertVC = [UIAlertController alertControllerWithTitle:@"" message:@"\n\n\n\n\n\n\n\n\n" preferredStyle:UIAlertControllerStyleActionSheet];
                //初始化一个标题为“选择时间”，风格是ActionSheet的UIAlertController，其中"\n"是为了给DatePicker腾出空间
                WeakSelf;
                UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                    //点击确定按钮的事件处理
                    __strong typeof(self) strongSelf = weakSelf;
                    [strongSelf->timeArray replaceObjectAtIndex:(currentIndex-2)/2 withObject:[self dateToString:_datePicker.date]];
                    [weakSelf creatDetailDict:weakSelf.NewRecordArray[(currentIndex-2)/2]];
                    [tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:currentIndex inSection:selectedIndex]] withRowAnimation:UITableViewRowAnimationFade];

                }];
                
                _datePicker = [[UIDatePicker alloc] init];//初始化一个UIDatePicker
                _datePicker.datePickerMode = UIDatePickerModeDateAndTime;
                [_datePickAlertVC.view addSubview:_datePicker];//将datePicker添加到UIAlertController实例中
                [_datePickAlertVC addAction:cancel];//将确定按钮添加到UIAlertController实例中
            }
            [self presentViewController:_datePickAlertVC animated:YES completion:^{
            }];//通过模态视图模式显示UIAlertController，相当于UIACtionSheet的show方法
        }
    }
}

- (NSString *)dateToString:(NSDate *)date {
    
    NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"GMT+0800"];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    [formatter setDateFormat:@"yyyy-MM-dd hh:mm"];
    
    [formatter setTimeZone:timeZone];
    
    NSString * timeString = [formatter stringFromDate:date];
    
    return timeString;
}

-(void)saveClick{
    for (NSString *time in timeArray) {
//        if (time.length == 0) {
//            [self.view makeToast:@"请选择囊液抽取时间！"];
//            return;
//        }
    }
    for (Record *model in self.NewRecordArray) {
        [self creatDetailDict:model];
        model.savedStepCount = 6;
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            [model update];
        });
    }
    

    NXSeventhStepViewController *NXSeventhStepVC = [[NXSeventhStepViewController alloc] init];
    NXSeventhStepVC.NewRecordArray = self.NewRecordArray;
    [self.navigationController pushViewController:NXSeventhStepVC animated:YES];
}
-(void)creatDetailDict:(Record *)model{
    NSInteger index = [self.NewRecordArray indexOfObject:model];
    NSDictionary *questionDict = [NSDictionary dictionaryWithObjectsAndKeys:
                                  @"1号管", KEY_RECORD_QUESTION,
                                  TYPE_QUESTION_SELECT, KEY_RECORD_TYPE,
                                  finish1Array[index][0], KEY_RECORD_ANSWER, nil];
    NSDictionary *question2Dict = [NSDictionary dictionaryWithObjectsAndKeys:
                                  @"2号管", KEY_RECORD_QUESTION,
                                  TYPE_QUESTION_SELECT, KEY_RECORD_TYPE,
                                  finish1Array[index][1], KEY_RECORD_ANSWER, nil];
    NSDictionary *question3Dict = [NSDictionary dictionaryWithObjectsAndKeys:
                                   @"3号管", KEY_RECORD_QUESTION,
                                   TYPE_QUESTION_SELECT, KEY_RECORD_TYPE,
                                   finish1Array[index][2], KEY_RECORD_ANSWER, nil];
    NSDictionary *question4Dict = [NSDictionary dictionaryWithObjectsAndKeys:
                                   @"6.2、囊液抽取时间。", KEY_RECORD_QUESTION,
                                   TYPE_QUESTION_DEFAULT, KEY_RECORD_TYPE,
                                   timeArray[index], KEY_RECORD_ANSWER, nil];
    NSDictionary *question5Dict = [NSDictionary dictionaryWithObjectsAndKeys:
                                   @"6.3、装有囊液的1.5mL EP置于冰上临时保存。", KEY_RECORD_QUESTION,
                                   TYPE_QUESTION_SELECT, KEY_RECORD_TYPE,
                                   finish2Array[index], KEY_RECORD_ANSWER, nil];
    
    
    NSArray *qustionArr = [NSArray arrayWithObjects:questionDict,question2Dict,question3Dict, question4Dict, question5Dict, nil];
    
    NSMutableDictionary *tempDict = [model getDetailDict];
    [tempDict setObject:qustionArr forKey:KEY_STEP6];
    [model setDetailDict:tempDict];
    NSLog(@"tempDict %@", tempDict);
    model.recordDetail = [tempDict JSONString];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)cancelclick{
    UIViewController*miloViewControl=(UIViewController *)[[self.navigationController viewControllers]objectAtIndex:1];
    [self.navigationController popToViewController:miloViewControl animated:YES];
}

-(void)nextStepClick{
    for (Record *model in self.NewRecordArray) {
        model.savedStepCount = 6;
    }

    NXSeventhStepViewController *NXSeventhStepVC = [[NXSeventhStepViewController alloc] init];
    NXSeventhStepVC.NewRecordArray = self.NewRecordArray;
    NXSeventhStepVC.fromtype = @"search";
    [self.navigationController pushViewController:NXSeventhStepVC animated:YES];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
